package Kernel;

import java.util.ArrayList;

/**
 * Selects behavior - to put in control - according priority model.
 *
 * @author Robin Lilja
 * @version 2009-09-22 1030h
 *
 */
public class BehaviorSelector extends ArrayList<Behavior> implements
		IBehaviorSelector {

	/**
	 * Current behavior in control.
	 */
	private int currentBehavior;

	/**
	 * Gets the name of the current behavior in control.
	 *
	 * @return Name of behavior as a string
	 */
	public String getCurrentBehavior() {

		return this.get(currentBehavior).toString();
	}

	/**
	 * Constructor of the behavior selector.
	 */
	public BehaviorSelector() {

		// Set initial behavior to the one with the lowest priority
		currentBehavior = this.size();
	}

	/**
	 * Loads behavior to the selector. Behavior will have lowest priority
	 * relative the previously loaded ones.
	 *
	 * @param b
	 *            Behavior to load
	 */
	public void load(Behavior b) {

		this.add(b);
	}

	/**
	 * Selects and runs behavior according priority model.
	 */
	public void select() {

		// Iterate the behaviors
		for (int i = 0; i < this.size(); i++) {

			// Check if behavior is ready to take control
			if (this.get(i).isReady() == true) {

				// If different behavior found
				if (i != currentBehavior) {

					// Stop the current behavior in control
					this.get(currentBehavior).stop();
				}

				// Update the current behavior
				currentBehavior = i;

				// Let new behavior take control
				this.get(i).run();
			}
		}
	}

}
